package com.mlnx.push.websocket.server.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.mlnx.mptp.push.PushPacket;
import com.mlnx.tp.base.utils.LogUtils;

import org.shan.mq.session.core.SessionManager;
import org.shan.mq.session.core.SessionManagerFactory;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;

/**
 * Created by amanda.shan on 2019/9/27.
 */
public class WebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    private SessionManager sessionManager = SessionManagerFactory.getInstance().getSessionManager();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {

        if (frame instanceof TextWebSocketFrame) {
            TextWebSocketFrame textWebSocketFrame = (TextWebSocketFrame) frame;
            String text = textWebSocketFrame.text();

//             LogUtils.i("收到设备内容:" + text);

            try {
                PushPacket pushPacket = JSON.parseObject(text, PushPacket.class);
                ctx.fireChannelRead(pushPacket);
            } catch (JSONException e) {
                LogUtils.e("非法json数据:" + text);
            }

        } else {
            String message = "unsupported frame type: " + frame.getClass().getName();
            throw new UnsupportedOperationException(message);
        }
    }
}
